package main

import (
	"log"
	"vov.cx/lib/runtime/redis"
	"vov.cx/lib/runtime/sql"
	"vov.cx/lib/runtime/sys"

	"github.com/gin-gonic/gin"
)

func statusSql(c *gin.Context) {
	gdb := sql.Get(c.Request.Context())
	if gdb == nil {
		c.JSON(500, gin.H{"msg": "no db provided"})
		return
	}

	db, err := gdb.DB()
	if err != nil {
		c.JSON(500, gin.H{"msg": err.Error()})
		return
	}

	if err := db.PingContext(c.Request.Context()); err != nil {
		c.JSON(500, gin.H{"msg": err.Error()})
		return
	}

	stats := db.Stats()
	c.IndentedJSON(200, stats)
}

func statusRedis(c *gin.Context) {
	conn, err := redis.GetConn(c.Request.Context())
	if err != nil {
		c.JSON(500, gin.H{"msg": err.Error()})
		return
	}

	reply, err := conn.Do("ping")
	if err != nil {
		c.JSON(500, gin.H{"msg": err.Error()})
		return
	}

	c.JSON(200, gin.H{"msg": reply})
}

func statusApp(c *gin.Context) {
	c.JSON(200, sys.GetAppStatus())
}

func handleStatus(statusMux *gin.Engine) {
	handleAny(statusMux, "/sys/status/sql", statusSql)
	handleAny(statusMux, "/sys/status/redis", statusRedis)
	handleAny(statusMux, "/sys/status/app", statusApp)
}

func handle(mux gin.IRoutes, method, relativePath string, handler gin.HandlerFunc) {
	mux.Handle(method, relativePath, handler)
	log.Printf("[ROUTER] %-30s %s", relativePath, "["+method+"]")
}

func handleAny(mux gin.IRoutes, relativePath string, handler gin.HandlerFunc) {
	mux.Handle("GET", relativePath, handler)
	mux.Handle("POST", relativePath, handler)
	log.Printf("[ROUTER] %-30s %s", relativePath, "[GET POST]")
}
